package com.iamback.dy.examine.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.iamback.dy.config.redis.RedisTemplateUtil;
import com.iamback.dy.entity.AgainContentExamineView;
import com.iamback.dy.entity.ContentExuser;
import com.iamback.dy.entity.DyContexts;
import com.iamback.dy.entity.ExContentView;
import com.iamback.dy.entity.UserAssign;
import com.iamback.dy.examine.common.Page;
import com.iamback.dy.examine.config.httpconfig.HttpAPIService;
import com.iamback.dy.examine.config.httpconfig.HttpResult;
import com.iamback.dy.examine.service.IContentExuserService;
import com.iamback.dy.mapper.ContentExuserMapper;
import com.iamback.dy.mapper.UserAssignMapper;
 
@Service
public class ContentExuserServiceImpl   implements IContentExuserService {

	@Value("${DY.EX.HTTPURL}")
	private String httpUrl;
	
	@Value("${DY.EX.TOKEN}")
	private String token;
	
	@Autowired
    private ContentExuserMapper contentExuserMapper;
	
	@Autowired
	private HttpAPIService apiService;
	@Autowired
	private RedisTemplateUtil redisTemplateUtil;
	@Autowired
	private UserAssignMapper assignMapper;
	@Override
	public ContentExuser findContentExuserById(Long id){
		return contentExuserMapper.findContentExuserById(id);
		
	}
	@Override
	public  void updateContentExuser(ContentExuser contentExuser){
		  contentExuserMapper.updateContentExuser(contentExuser);
	}
	
	@Override
	public void saveList(List<ContentExuser> contentExusers) {
		contentExuserMapper.inserContentExuser(contentExusers);
	}
 
	/**
	 * 审核任务分配（审核人员）
	 * @param userId
	 * @param
	 */
	@Async("distributionAsync")
	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED)
	public synchronized void distributionBy (String userId,String dyId,Integer size){
		Map<String, Object> map = new HashMap<String, Object>();
		if(userId!=null){
			if(size!=null&&size<20){//当前用户下未审核小于20 开始分配新审核段子
				map =new HashMap<String, Object>();
				map.put("exResult", "0");
				map.put("exuserIdnot", "123");
				map.put("size", 100-size);
				
				UserAssign userAssign= assignMapper.getUserAssignByUserId(Integer.parseInt(userId));
				if(userAssign !=null){
					if(userAssign.getAssignType()==2){
						map.put("contentType", "3");
					}else if(userAssign.getAssignType()==3){
						map.put("contentType", "4");
					}
				}
				List<ContentExuser> pageContentExusers=contentExuserMapper.findContentExuserBy(map);
				for(ContentExuser contentExuser:pageContentExusers){
					ContentExuser exuserContentExuser =new ContentExuser();
					exuserContentExuser.setId(contentExuser.getId());
					exuserContentExuser.setExuserId(Long.valueOf(userId));
					exuserContentExuser.setExResult("0");
					exuserContentExuser.setAllotTime(new Date()); 
					contentExuserMapper.updateContentExuserAllot(exuserContentExuser);
				}
		     }
		}else if(dyId !=null){ 
			if(size!=null&&size <20){
				map = new HashMap<String, Object>();
				map.put("exResult", "0");
				map.put("exuserIdnot", "123");
				map.put("size", 100-size);
				List<ContentExuser> pageContentExusers=contentExuserMapper.findContentExuserBy(map);
				for(ContentExuser contentExuser:pageContentExusers){
					ContentExuser exuserContentExuser =new ContentExuser();
					exuserContentExuser.setId(contentExuser.getId());
					exuserContentExuser.setExdyId(dyId);
					exuserContentExuser.setExuserId(Long.valueOf(0));
					exuserContentExuser.setExResult("0");
					exuserContentExuser.setAllotTime(new Date()); 
					contentExuserMapper.updateContentExuserAllot(exuserContentExuser);
				}
			}
		}
	} 
	
	/**
	 * app 用户审核
	 */
	@Override
	public Long upateExConten(ContentExuser exuserContent) {
		Long countNum= 0L;
		if(exuserContent!=null&&exuserContent.getId()!=null){
			ContentExuser dbContentExuser= contentExuserMapper.findContentExuserById(exuserContent.getId());
			if(dbContentExuser.getExResult().equals("0")&&exuserContent.getExuserId()==dbContentExuser.getExuserId()){
				dbContentExuser.setExResult(exuserContent.getExResult());
				dbContentExuser.setOperationCode(exuserContent.getOperationCode());
				dbContentExuser.setExTime(new Date()); 
				dbContentExuser.setExDesc(null);
				dbContentExuser.setExuserId(exuserContent.getExuserId());
				if(exuserContent.getExResult().equals("1")||exuserContent.getExResult().equals("2")){
					try {
						postExResultHttp(dbContentExuser.getDyContentId(), exuserContent.getExResult());
						dbContentExuser.setSysStatus("2");//设置同步状态
						contentExuserMapper.updateContentExuser(dbContentExuser);
						countNum=setExtaskNum(exuserContent.getExuserId()); 
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return countNum;
	}
	
	public Long setExtaskNum(Long exuserId){
		Long num = 0L;
		String value = (String) redisTemplateUtil.get("exuser:taks:num:"+exuserId);
		if(value !=null && !value.equals("")){
			num = Long.valueOf(value)+1;
		}else{
			num= num+1;
		}
		redisTemplateUtil.set("exuser:taks:num:"+exuserId,String.valueOf(num),36000);
		return num;
	}
	
	@Override
	public Long getExtaskNum(Long exuserId){
		Long num = 0L;
		String value = (String) redisTemplateUtil.get("exuser:taks:num:"+exuserId);
		if(value !=null && !value.equals("")){
			num = Long.valueOf(value);
		}
		return num; 
	}
	
	
	@Override
	public Map<String, Object> updateExDyIdContent(ContentExuser exuserContent){
		Map<String, Object> map = new HashMap<String, Object>();
		ContentExuser contentExuser=contentExuserMapper.findByDyId(exuserContent);
		if(contentExuser!=null){
			contentExuser.setOperationCode(exuserContent.getOperationCode());
			contentExuser.setExResult(exuserContent.getExResult());
			contentExuser.setExTime(new Date());
			try {
				postExResultHttp(contentExuser.getDyContentId(), contentExuser.getExResult());
				contentExuser.setSysStatus("2");//设置同步状态
				contentExuserMapper.updateContentExuser(contentExuser);
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put("respMessage", "ok");
			map.put("respCode", "0");
			map.put("isUsed", true);
		}else{
			map.put("respMessage", "当前审核以无效，请刷新！");
			map.put("respCode", "");
			map.put("isUsed", false);
		}  
		return map;
	}
	
	
	@Async("distributionAsync")
	public  void  postExResultHttp(Long dyContentId ,String exResult) throws Exception{
		//1qaz@WSX1234QWER
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("dyID", 3991234);
		params.put("type", 4);
		params.put("operator", Integer.parseInt(exResult));
		List<Integer> dyDataID =new ArrayList<Integer>();
		dyDataID.add(dyContentId.intValue());
		params.put("dyDataID", dyDataID);
		params.put("token", token);
		params.put("deviceID",String.valueOf(System.currentTimeMillis()));
		HttpResult vss= apiService.doPostJson(httpUrl, JSON.toJSONString(params)); 
		System.out.println(vss.getBody());
	}
	
	@Override
	public List<DyContexts> findContentExuserByDyId(String dyId,Long countentId,Integer pageNum,Integer numPerPage){
		 int start = pageNum ==0?0:(pageNum-1)*numPerPage;
		 Map<String, Object> map =new HashMap<String, Object>();
		 map.put("dyId", dyId);
		 map.put("dyContentId", countentId);
		 map.put("pageNum", start);
		 map.put("numPerPage", numPerPage);
		return contentExuserMapper.findContentExuserByDyId(map);
	}
	
	
	@Override
	public Page<ExContentView> findContentExuserByUserId(Integer userId, Integer  pageNumber, Integer pageSize){
		int start = pageNumber ==0?0:(pageNumber-1)*pageSize;
		Map<String, Object> pageable =new HashMap<String, Object>();
		pageable.put("exuserId", userId);
		pageable.put("pageNum", start);
		pageable.put("numPerPage", pageSize);
		Page<ExContentView> page = new Page<ExContentView>();
		Integer count =  contentExuserMapper.findContentExuserByUserIdCount(pageable);
		if(count!=null &&count>0){
			page.setContent(contentExuserMapper.findContentExuserByUserId(pageable));
			page.setTotalElements(count); 
		}else{ 
			page.setTotalElements(0);
		}
		return page;
	}
	
//	/**
//	 * APP 用户分配审核 段子
//	 * @param userId
//	 * @param roleId
//	 */
//	public void distributionByDyUser(String dyUserId ){
//		SimpleSpecificationBuilder<ContentExuser> builder = new SimpleSpecificationBuilder<ContentExuser>();
//		builder.add("dyId", Operator.eq.name(), dyUserId);
//		builder.add("userId", Operator.eq.name(),userId);
//		contentExuserDao.getOne(id);
//	}
	@Override
	public void updateContentExuserBlocked(String publisherDyId) {
		ContentExuser contentExuserDyId =new  ContentExuser();
		contentExuserDyId.setPublisherDyId(publisherDyId);
		contentExuserDyId.setExResult("0");
		List<ContentExuser> contentExusers = contentExuserMapper.findByBlocked(contentExuserDyId);
		for(ContentExuser contentExuser:contentExusers){
			contentExuser.setExResult("3"); 
			contentExuser.setExTime(new Date()); 
			contentExuser.setExDesc("禁言操作");
			contentExuser.setExuserId(null);
			contentExuser.setOperationCode(null);
			try {
				postExResultHttp(contentExuser.getDyContentId() ,"2");
				contentExuserMapper.updateContentExuserBlocked(contentExuser);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Page<AgainContentExamineView> findAgainContentExamineByPage(Integer userId, Date starDate, Integer pageNum, Integer numPerPage) {
		
		int start = pageNum ==0?0:(pageNum-1)*numPerPage;
		Map<String, Object> map  = new HashMap<String, Object>();
		map.put("exuserId", userId);
		map.put("exTime", starDate);
		map.put("pageNum", start);
		map.put("numPerPage", numPerPage); 
		Page<AgainContentExamineView> page = new Page<AgainContentExamineView>();
		Integer count = contentExuserMapper.findAgainContentExamineByPageCount(map);
		if(count!=null && count>0){
			page.setContent(contentExuserMapper.findAgainContentExamineByPage(map));
			page.setTotalElements(count);
		}
		return page;
	}
 
}
